package zxs.sino.elite.hub.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import zxs.sino.elite.hub.constant.UrlConstant;
import zxs.sino.elite.hub.exception.BizCodeEnums;
import zxs.sino.elite.hub.exception.RRException;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 *
 * @author zhang
 */
@Component
public class WeChatUtil {

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;


    /**
     * 获取微信小程序AccessToken
     *
     */
    public String getAccessToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String response = HttpUtil.get(UrlConstant.WX_ACCESS_TOKEN_URL, map);
        try {
            JsonNode jsonNode = objectMapper.readTree(response);
            if (jsonNode.has("access_token")) {
                return jsonNode.get("access_token").asText();
            } else {
                throw new RRException(BizCodeEnums.IDEMPOTENT_TOKEN_CREATE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            throw new RRException("解析微信AccessToken响应失败: " + e.getMessage());
        }
    }

    /**
     * 小程序登录 - 通过code获取openid
     *
     * @param code 小程序前端传来的code
     */
    public String getOpenId(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.get(UrlConstant.WX_LOGIN_URL, map);
        try {
            JsonNode jsonNode = objectMapper.readTree(response);
            if (jsonNode.has("openid")) {
                return jsonNode.get("openid").asText();
            } else {
                throw new RRException(BizCodeEnums.IDEMPOTENT_TOKEN_CREATE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            throw new RRException("解析微信OpenID响应失败: " + e.getMessage());
        }
    }

    /**
     * 通过临时code获取手机号
     *
     * @param phoneCode 前端getPhoneNumber事件返回的code
     * @return 手机号字符串
     */
    public String getPhoneNumber(String phoneCode) {
        String token = this.getAccessToken();

        // 构建请求体
        Map<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);

        String json = JSONUtil.toJsonStr(map);

        String response = HttpUtil.post(UrlConstant.WX_PHONE_NUMBER_URL + "?access_token=" + token, json);
        try {
            JsonNode jsonNode = objectMapper.readTree(response);
            if (jsonNode.has("phone_info")) {
                JsonNode phoneInfoNode = jsonNode.get("phone_info");
                if (phoneInfoNode.has("phoneNumber")) {
                    return phoneInfoNode.get("phoneNumber").asText();
                }
            }
            throw new RRException(BizCodeEnums.IDEMPOTENT_TOKEN_CREATE_EXCEPTION.getMsg());
        } catch (Exception e) {
            throw new RRException("解析微信手机号响应失败: " + e.getMessage());
        }
    }


}
